import {Body, Controller, Ctx, Get, Post} from "koa-ts-controllers";
import {LoginBody, RegisterBody} from '../validators/User'
import {User as UserModel} from '../models/User'
import * as Boom from "boom";
import {Context} from "koa";
import crypto from 'crypto'
import jwt from 'jsonwebtoken'
import configs from '../configs/index'
import authorization from "../middlewares/authorization";

@Controller("/user")
export class UserController {
    @Post('/register')
    async register(@Ctx() ctx: Context, @Body() body: RegisterBody) {
        let {name, password} = body
        //验证数据库是否存在要注册的用户
        let user = await UserModel.findOne({
            where: {
                name
            }
        })
        if (user) {
            throw Boom.conflict('注册失败', '用户名被注册')
        }
        let newUser = new UserModel();
        newUser.name = name;
        newUser.password = password;
        await newUser.save();
        return {
            id: newUser.id,
            name: newUser.name,
            createdAt: newUser.createdAt
        }
    }

    @Post("/login")
    async login(@Ctx() ctx: Context, @Body() body: LoginBody) {
        let {name, password} = body
        console.log(name + password)
        let user = await UserModel.findOne({
            where: {name}
        });
        if (!user) {
            throw Boom.notFound('登录失败', '用户不存在')
        }
        let md5 = crypto.createHash('md5');
        password = md5.update(password).digest('hex');
        if (password != user.password) {
            throw Boom.forbidden('登录失败', '密码错误')
        }

        let userInfo = {
            id: user.id,
            name: user.name,
        }
        let token = jwt.sign(userInfo, configs.jwt.privateKey)
        ctx.set('authorization', token)
        return userInfo
    }

    @Get('/auth')
    // @Flow([authorization])
    async authText(@Ctx() ctx: Context) {
        return '不登录看不到'
    }

    @Get('/noauth')
    async no() {
        return '随便看'
    }
}
